package mall.service;

import mall.repository.ProductDao;
import mall.repository.CartDao;
import mall.entity.Cart;

import java.util.List;

public class CartService {

    private final CartDao cartDao = new CartDao();
    private final ProductDao productDao = new ProductDao();

    public int save(Cart cart) {
        return cartDao.insert(cart);
    }

    public List<Cart> list(Integer userId) {
        List<Cart> list = cartDao.selectListByUserId(userId);
        if (!list.isEmpty()) {
            for (Cart cart : list) {
                cart.setProduct(productDao.selectById(cart.getProductId()));
            }
        }

        return list;
    }

    public int update(Cart cart) {
        if (cart.getQuantity() == 0) {
            cart.setQuantity(1);
        }
        return cartDao.updateQuantityById(cart.getQuantity(), cart.getId());
    }

    public int remove(Integer cartId) {
        return cartDao.deleteById(cartId);
    }

    public int selected(Integer selected, Integer cartId) {
        return cartDao.updateSelectedById(selected, cartId);
    }

    public boolean exist(Integer userId, Integer productId) {
        return cartDao.getByUserIdAndProductId(userId, productId);
    }
}
